/*
 * btvpms: com.ctvit.framework.web.upload.FileDownloadServlet.java Create On Jun 5, 2009 3:26:53 PM By Q-Wang
 * $Revision: 1.8 $
 */
package com.ctvit.framework.web.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ctvit.framework.security.LdapPasswordEncoder;
import com.ctvit.framework.web.context.ContextHolder;
import com.ctvit.sms.platform.domain.Login;
import com.ctvit.sms.platform.service.AppOnlyService;
import com.ctvit.struts.common.CommonFunc;

/**
 * 文件下载Servlet.
 * 
 * TODO MimeType 大小写敏感问题(e.g. *.DOC变成默认ContentType,是否需要上传时扩展名转小写?)
 * @author Q-Wang
 */
public class FileDownloadServlet extends HttpServlet {
	protected final Log log = LogFactory.getLog(getClass());
	/**
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean validFail=CommonFunc.validateRequest(request);
//		validFail=false;
		request.setCharacterEncoding("gbk");
		String noticeId=request.getParameter("id");
//		noticeId=URLDecoder.decode(noticeId);
//		noticeId=new String(noticeId.getBytes("ISO-8859-1"),"UTF-8");
		String newNoticeId=request.getParameter("newid");
		String url=request.getParameter("fileUrl");//?fileUrl=attached/31528/M002.txt
		boolean needAttachment = false;      //手机端要用直接打开的方式，网站需要用下载的方式
		if(StringUtils.isNotEmpty(url)) {
			needAttachment = true;
		}
		boolean badReq=false;String filename="";
		if (StringUtils.equals(CommonFunc.sysid,"remote")){
			if (validFail==true){
				badReq=true;
			}else{
				String sqlString="";
				AppOnlyService appOnlyService=ContextHolder.getBean(AppOnlyService.class);
				if (!StringUtils.isEmpty(noticeId)){
					String[] ary=noticeId.split("\\|");
					sqlString="select filename from notice_file where noticeid='"+ary[0]+"' and fileid='"+ary[1]+"'";
					List<Map<String, String>> fileList=appOnlyService.execSql(sqlString);
					filename=fileList.get(0).get("filename");
					url="/attached/"+ary[0]+"/"+filename;
				}
				if (!StringUtils.isEmpty(newNoticeId)){
					String[] ary=newNoticeId.split("\\|");
					sqlString="select f_file_name from t_attach where f_object_key='"+ary[0]+"' and f_attach_no='"+ary[1]+"'";
					List<Map<String, String>> fileList=appOnlyService.execSql(sqlString);
					filename=fileList.get(0).get("f_file_name");
					url="attached/newsite/"+ary[0]+"/"+filename;
				}
			}
		}else{
			if (url==null||url.equals("")) {
				badReq=true;
			}else{
				filename = url.substring(url.lastIndexOf("/")+1);
			}
		}
		if (badReq) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		} else {
			if (needAttachment == true) {
				response.addHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
			} else {
				response.addHeader("content-disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
			}
			log.debug("download url="+url);
			response.setContentType("application.x-msdownload");
			File file = new File(request.getRealPath("/")+"/"+url);// 得到要下载的文件
			int fileSize = (int) file.length();
			InputStream is = new FileInputStream(file);
			response.setContentLength(fileSize);
	        ServletOutputStream sos = response.getOutputStream();
	        byte[] data = new byte[2048];
	        int len = 0;
	        while ((len = is.read(data)) > 0) {
	            sos.write(data, 0, len);
	        }
	        is.close();
	        sos.close();
//			request.getRequestDispatcher(url).forward(request, response);
		}
	}
}
